import React from 'react';
import { connect } from 'dva';
import { Button, Table, Form, Input, InputNumber,Popconfirm,DatePicker, Select,TreeSelect,Row, Col,message} from 'antd';

import AddModal from '../../components/asset/DynamicSearchModal';
import SearchModal from '../../components/asset/SearchModal';

const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const RangePicker = DatePicker.RangePicker;
const formItemLayout = {
    wrapperCol: { className: 'wrapper-col' },
}


function DynamicSearch ({ dispatch, dynamicSearch, loading, form }) {
    
    const { getFieldDecorator, getFieldsValue, getFieldValue } = form;
    const {  modalVisible, modalType,roomList,assetTypeTree,assetBrandList,rackList,assetModelList,
        existsSerialNo,attrValues,groupList,typeId,brandId,assetId,typeAttrGroup,
        attrValuesForm ,assetData,selectType,searchModalShow} = dynamicSearch

        const getSelectOption = (str) => {
            var list = str.split(",");
            return list.map((d,index)=>(<Option key={index} value={d}>{d}</Option>))
        }
        
        const getallForm = (list)=>list.map((d,index)=>(
            <div key={index}>              
              <Row gutter={16}>
                {getFormItemList(d.attrList)}
              </Row>
            </div>
        ))
        
        const getFormItemList = (list) => list.map((d,index)=>(            
            <Col key={index} span={index>0?(index%4==0?4:5):5}>
              {getSwitchItem(d)}
            </Col>
        ))
        
        const getSwitchItem = (item) => {
            switch(item.type){
              case 1:
                return (
                    <FormItem
                      {...formItemLayout}
                      style={{ width: '100%' }} 
                    >
                      {
                       form.getFieldDecorator(item.id_)(<Input  placeholder={item.lable} style={{ width: '100%' }} />)
                      }
                    </FormItem>
                )
              case 2:
                return (
                    <FormItem
                      {...formItemLayout}
                      style={{ width: '100%' }} 
                    >
                      {
                       form.getFieldDecorator(item.id_)(<InputNumber placeholder={item.lable} style={{width: "100%"}} />)
                      }
                    </FormItem>
                )
              case 3:
                return (
                    <FormItem
                      {...formItemLayout}
                      style={{ width: '100%' }} 
                    >
                      {
                       form.getFieldDecorator(item.id_)(<Input.TextArea placeholder={item.lable} style={{ width: '100%' }} />)
                      }
                    </FormItem>
                )
              case 4:
                return (
                    <FormItem
                      {...formItemLayout}
                      style={{ width: '100%' }} 
                    >
                      {
                        form.getFieldDecorator(item.id_)(
                          <Select  style={{ width: '100%' }} placeholder={item.lable}>
                            {getSelectOption(item.options)}
                          </Select>
                        )
                      }
                    </FormItem>
                )
              case 5:
                return (
                    <FormItem
                      {...formItemLayout}
                      style={{ width: '100%' }} 
                    >
                      {
                       form.getFieldDecorator(item.id_)(<DatePicker placeholder={item.lable} format="YYYY-MM-DD"  style={{ width: '100%' }}  showToday/>)
                      }
                    </FormItem>
                )
              default:
                return null;
            }
          }
        

    const columns = [{
            title: '资产编号',
            dataIndex: 'assetNo',
            key: 'assetNo',
            width: 150,
        },{
            title: '设备序列号',
            dataIndex: 'serialNo',
            key: 'serialNo',
            width: 150,
        },{
            title: '资产分类',
            dataIndex: 'typeName',
            key: 'typeName',
            width: 120,
        },{
            title: '设备名称',
            dataIndex: 'assetName',
            key: 'assetName',
            width: 150,
        },{
            title: '品牌',
            dataIndex: 'brandName',
            key: 'brandName',
            width: 100,
        },{
            title: '设备型号',
            dataIndex: 'modelName',
            key: 'modelName',
            width: 120,
        },{
            title: 'RFID号',
            dataIndex: 'rfidNo',
            key: 'rfidNo',
            width: 100,
        },{
            title: 'IP地址',
            dataIndex: 'ip',
            key: 'ip',
            width: 100,
        },{
            title: '所在位置',
            dataIndex: 'roomName',
            key: 'roomName',
            width: 160,
        },{
            title: '所在机柜',
            dataIndex: 'rackName',
            key: 'rackName',
            width: 120,
        },{
            title: 'U位',
            dataIndex: 'startU',
            key: 'startU',
            width: 100,
            render: (value, row, index) => {
                var u;
                if(row.startU){
                    u =row.startU;
                    if(row.endU){
                        u= row.startU+'-'+row.endU;
                    }
                }
                return (
                    u
                )
            }
        },{
            title: '设备状态',
            dataIndex: 'statusName',
            key: 'statusName',
            width: 80
        },{
            title: '是否借用',
            dataIndex: 'isBorrow',
            key: 'isBorrow',
            width: 80,
            render: (value, row, index) => {
                return (
                    value == 1 ? "借用" : '未借用'
                )
            }
        },{
            title: '是否分配',
            dataIndex: 'isDistribute',
            key: 'isDistribute',
            width: 80,
            render: (value, row, index) => {
                return (
                    value == 1 ? "已分配" :'未分配'
                )
            }
        },{
            title: '管理部门',
            dataIndex: 'manageBranchName',
            key: 'manageBranchName',
            width: 120,
        },{
            title: '领用部门',
            dataIndex: 'branchName',
            key: 'branchName',
            width: 120,
        },{
            title: '领用人',
            dataIndex: 'endUserName',
            key: 'endUserName',
            width: 100,
        },{
            title: '操作',
            key: 'operation',
            width: 80,
            fixed: 'right',
            render: (text, record) => (
                <span>
                <a onClick={onEditItem.bind(null, record.id_, record.typeId_,)}>查看详情</a>
                </span>
            ),
    }];

    const pagination = {
        current:dynamicSearch.current,
        pageSize:dynamicSearch.currentSize,
        total: dynamicSearch.total,
        showSizeChanger: true,
        showTotal: (total => '共' + dynamicSearch.total + '条'),
        onShowSizeChange(current, size) {
            dispatch({
                type: 'dynamicSearch/queryList',
                payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':size} },
            });
        },
        onChange(current) {
            dispatch({
                type: 'dynamicSearch/queryList',
                payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':dynamicSearch.currentSize} },
            });
        },
    };
    
    const submitHandle = () => {      
        var dynamicParamList =[];
        var objString =JSON.stringify({ ...getFieldsValue() });
        var obj =getFieldsValue();
        for(var i=0;i<typeAttrGroup.length;i++){
            var typeAttrs =typeAttrGroup[i].attrList;           
           for(var j=0;j<typeAttrs.length;j++){            
              if(objString.indexOf(typeAttrs[j].id_)>0){
                dynamicParamList.push({type:typeAttrs[j].type,id:typeAttrs[j].id_,value:obj[typeAttrs[j].id_]});
              }
           }
        }
        dispatch({
            type: 'dynamicSearch/queryList',
            payload: { ...getFieldsValue() ,dynamicParamList:dynamicParamList},
        });
    }

    function handleClear(){
      form.resetFields();
    }

    const onEditItem = (id,typeId,) => {
        dispatch({
            type: 'dynamicSearch/qryById',
            payload:id,
        })
        dispatch({
            type: 'dynamicSearch/qryAttrValue',
            payload:{assetId:id,typeId:typeId},
        })
    }

    const modalProps = {
        visible: modalVisible,
        type: modalType,
        groupList:groupList||[],
        attrValues:attrValues||[],
        attrValuesForm:attrValuesForm||{},
        assetData:assetData,
        maskClosable: false,
        confirmLoading: loading,
        title: '配置资产属性',
        wrapClassName: 'vertical-center-modal',
        newKey : dynamicSearch.newKey,
        onOk (data) {
            dispatch({
                type: `dynamicSearch/queryList`,
                payload: data,
            })
        },
        onCancel () {
            dispatch({
                type: 'dynamicSearch/hideModal',
            })
        },
      
    }

    const loopRoom = data => data.map((item) => {
      return <Option key={item.id_ + ''}>{item.name}</Option>
    });
    const loopBrand = data => data.map((item) => {
      return <Option key={item.id_ + ''}>{item.name}</Option>
    });
    const getRack = data => data.map((item) => {
        return <Option key={item.id_+''}>{item.assetName}</Option>
    })
    const treeData = (i) => {
        return i.map( d => {
          d.label = d.name;
          d.key = d.id_+'';
          d.value = d.id_+'';
          d.children = d.assetType && d.assetType.length > 0 ? treeData(d.assetType) : [];
          return d;
        })
    }

    const roomChange= (data) => {
        form.setFieldsValue({rackId: undefined});
        dispatch({
            type: 'dynamicSearch/qrySearchRackList',
            payload: data,
        })
    }

    const typeChange= (data) => {
        dispatch({
            type: 'dynamicSearch/qryAttrByTypeId',
            payload: {typeId:data,},
        });
    }

    // 显示高级搜索
    function showAdvancedSearch(){
        if(getFieldValue("typeId")){
            dispatch({
                type: 'dynamicSearch/updateState',
                payload: {searchModalShow:true,},
              });
        }else{
            message.error("请选择一种资产分类")
        }      
    }

     // 隐藏高级搜索
    function hideAdvancedSearch(){
        dispatch({
            type: 'dynamicSearch/updateState',
            payload: {searchModalShow:false,},
        });
    }

    return (
        <div style={{backgroundColor:'#fff'}}>
          <div style={{minHeight:'100%'}}>
            <div style={{width:'100%',backgroundColor:'#fff',lineHeight:'40px',paddingLeft:'20px',paddingTop:'10px', paddingRight:'20px'}}>
                <Form layout="inline" style={{width:'100%'}}>
                <Row gutter={16}>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('assetName')(<Input  placeholder="请输入设备名称模糊查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('rfidNo')(<Input  placeholder="请输入RFID查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('assetNo')(<Input  placeholder="请输入资产编号查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('serialNo')(<Input  placeholder="请输入资产序列号查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={4}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('roomId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="选择机房/库房"
                                    optionFilterProp="children"
                                    onChange={roomChange}
                                    dropdownMatchSelectWidth={true}
                                    style={{ width: '100%' }}
                                >
                                <Option value="">全部</Option>
                                {loopRoom(dynamicSearch.roomList)}
                                </Select>
                                )
                            }
                            </FormItem>
                        </Col>           
                    </Row>
                    <Row gutter={16}>
                        <Col span={5}>
                        <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('rackId')(
                                <Select
                                    showSearch
                                    style={{ width:'100%' }}
                                    allowClear
                                    placeholder="请选择所在机柜"
                                >
                                <Option value="">全部</Option>
                                {getRack(dynamicSearch.searchRackList)}
                                </Select>
                                )
                            }
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('typeId')(
                                <TreeSelect
                                    style={{ width: '100%' }}
                                    showSearch
                                    treeNodeFilterProp="title"
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    placeholder="请选择资产分类"
                                    onChange={typeChange}
                                    allowClear
                                    treeDefaultExpandAll
                                    treeData={treeData(assetTypeTree)}
                                >                                
                                </TreeSelect>
                                )
                            }
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('brandId')(
                                <Select
                                    showSearch
                                    style={{ width: '100%' }}
                                    placeholder="选择品牌"
                                    optionFilterProp="children"
                                >
                                <Option value="">全部</Option>
                                {loopBrand(assetBrandList)}
                                </Select>
                                )
                            }
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('status')(
                                <Select
                                    showSearch
                                    style={{ width: '100%' }}
                                    placeholder="选择状态"
                                    optionFilterProp="children"
                            >
                                <Option value="">全部</Option>
                                <Option value="1">已入库</Option>
                                <Option value="2">已上架</Option>
                                <Option value="3">已报废</Option>
                                <Option value="4">已出库</Option>

                                </Select>
                            )}
                            </FormItem>
                        </Col>
                        <Col span={4}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('ip')(<Input  placeholder="请输入IP查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        </Row>
                            {searchModalShow?getallForm(typeAttrGroup):""}
                        <Row gutter={16}>
                            <Col span={24} style={{ textAlign:'right',paddingRight:0}}>
                            <FormItem>
                            <Button type="primary" size='large' onClick={submitHandle} className='ant-search-btn'>查询</Button>
                            </FormItem>
                            <FormItem>
                            <Button size="large" htmlType="reset" onClick={handleClear}>清空</Button>
                            </FormItem>
                            {searchModalShow?<FormItem>
                                <Button size="large" onClick={hideAdvancedSearch}>隐藏搜索</Button>
                            </FormItem>:<FormItem>
                                <Button size="large" onClick={showAdvancedSearch}>高级搜索</Button>
                            </FormItem>}
                            
                            </Col>
                        </Row>                      
                </Form>
            </div>
            <div style={{width:'100%',padding:"30px 20px",}}>
                <Table columns={columns} rowKey={record => record.id_} scroll={{ x: 2220 }} loading={loading} dataSource={dynamicSearch.list} pagination={pagination}
                />
            </div>
            </div>
               <AddModal {...modalProps} />
        </div>
    );
}

function mapStateToProps(state) {
  return { dynamicSearch : state.dynamicSearch,loading:state.loading.models.dynamicSearch};
}

DynamicSearch = Form.create()(DynamicSearch);

export default connect(mapStateToProps)(DynamicSearch);
